import { Controller, Get } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import MeiliSearch from 'meilisearch'

@Controller()
export class SearchController {
  private readonly meili: MeiliSearch

  constructor(
    config: ConfigService,
  ) {
    this.meili = new MeiliSearch({
      host: config.getOrThrow<string>('MEILISEARCH_HOST'),
      apiKey: config.getOrThrow<string>('MEILI_MASTER_KEY'),
    })
  }

  /** get api key for meili search */
  @Get()
  async getKey() {
    // access key is needed to use search
    const keys = await this.meili.getKeys()
    for (const key of keys.results) {
      if (
        key.actions.length === 2 && key.indexes.length === 2
        && key.actions.every(a => a === 'search' || a === 'stats.get')
        && key.indexes.every(i => i === 'bots' || i === 'servers' || i === 'comments')
      ) {
        return { key: key.key } // return key only, not other info about key
      }
    }

    // no key found, create one.
    const fallbackKey = await this.meili.createKey({
      actions: [ 'search', 'stats.get' ],
      indexes: [ 'bots', 'servers', 'comments' ],
      expiresAt: null,
    })

    return { key: fallbackKey.key }
  }
}
